package com.szxb.facebus.net.ftp;

import android.text.TextUtils;

import com.szxb.facebus.BusApp;
import com.szxb.facebus.util.basics.Utils;
import com.szxb.mlog.SLog;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.List;

import static com.szxb.facebus.net.ftp.FtpResponse.FAIL;
import static com.szxb.facebus.net.ftp.FtpResponse.FILE_NO_EXIT;
import static com.szxb.facebus.net.ftp.FtpResponse.NOUPDATE;
import static com.szxb.facebus.net.ftp.FtpResponse.SUCCESSFUL;

/**
 * 作者: Tangren on 2017/7/27
 * 包名：com.szxb.ftp
 * 邮箱：996489865@qq.com
 * TODO:FTP工具类
 */

public class FTPUtil {

    private String url;
    private int port = 21;
    private String username;
    private String password;
    private String path;
    private String ftpPath;
    private String[] fileName;
    private String sinfileName;
    private List<InputStream> input;
    private int isForce = -1;

    private String tag = "TAG";


    private String[] ftpPaths;
    private String packgeName;

    private String posSn;

    public FTPUtil builder(String url) {
        this.url = url;
        return this;
    }

    public FTPUtil setPort(int port) {
        this.port = port;
        return this;
    }

    public FTPUtil setLogin(String username, String psw) {
        this.username = username;
        this.password = psw;
        return this;
    }

    public FTPUtil setPath(String path) {
        this.path = path;
        return this;
    }

    public FTPUtil setFTPPath(String ftpPath) {
        this.ftpPath = ftpPath;
        return this;
    }

    public FTPUtil setFileName(String sinfileName) {
        this.sinfileName = sinfileName;
        return this;
    }

    public FTPUtil setFileName(String[] fileName) {
        this.fileName = fileName;
        return this;
    }

    public FTPUtil setInput(List<InputStream> input) {
        this.input = input;
        return this;
    }

    public FTPUtil setPackgeName(String packgeName) {
        this.packgeName = packgeName;
        return this;
    }

    public FTPUtil setPosSn(String posSn) {
        this.posSn = posSn;
        return this;
    }


    public String getTag() {
        return tag;
    }

    public FTPUtil setTag(String tag) {
        this.tag = tag;
        return this;
    }

    public FTPUtil setForce(int isForce) {
        this.isForce = isForce;
        return this;
    }

    public FtpResponse download(String fileType, String lineNo) {
        FtpResponse response = new FtpResponse();
        FTPClient ftp = new FTPClient();
        int reply;
        ftp.setConnectTimeout(5000);
        try {
            ftp.connect(url, port);// 连接FTP服务器
            ftp.login(username, password);// 登录
            //连接的状态码
            reply = ftp.getReplyCode();
            ftp.setDataTimeout(12000);
            //判断是否连接上ftp
            if (!FTPReply.isPositiveCompletion(reply)) {
                SLog.e("FTP(download.java:163)FTP连接失败>>tag=" + getTag());
                ftp.disconnect();
                return response;
            }

            SLog.d("FTP(download.java:168)FTP连接成功>>tag=" + getTag());

            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            ftp.setBufferSize(1024);
            ftp.setControlEncoding("UTF-8");
//            ftp.enterLocalPassiveMode();
            ftp.enterLocalActiveMode();
            FTPFile[] ftpFile = ftp.listFiles(ftpPath.substring(0, ftpPath.length() - 1));
            boolean isSuccess = false;
            for (FTPFile file : ftpFile) {
                if (file.getName().contains(fileType) && file.getName().contains(lineNo)) {
                    isSuccess = true;
                    baseDown(fileType, response, ftp, file);
                    break;
                }
            }

            if (!isSuccess) {
                response.setMsg("文件不存在");
                response.setIsOk(FILE_NO_EXIT);
            }

            ftp.logout();
            ftp.disconnect();
            //判断是否退出成功，不成功就再断开连接。
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    SLog.e("FTPUtil(download.java:188)IOException>>>>tag=" + getTag() + ">>" + Utils.getExectionStr(ioe));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (e instanceof ConnectException) {
                response.setMsg("FTP连接异常");
            } else {
                response.setMsg(e.getClass().getSimpleName());
            }
            SLog.e("FTPUtil(download.java:193)FTP异常>>tag=" + getTag() + ">>>" + Utils.getExectionStr(e));
        }
        return response;
    }


    private void baseDown(String fileType, FtpResponse response, FTPClient ftp, FTPFile file) throws IOException {
        response.setFileExit(true);
        if (TextUtils.equals(fileType, "FACE")) {
            String faceListFileName = BusApp.getPosManager().getFaceListFileName();
            if (TextUtils.equals(faceListFileName, file.getName()) && isForce < 0) {
                response.setIsOk(NOUPDATE);
                response.setMsg("人脸列表无需同步");
                SLog.d("FTPUtil(baseDown.java:187)人脸列表无需同步");
                return;
            }
        }

        BufferedOutputStream buffOut;
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        buffOut = new BufferedOutputStream(new FileOutputStream(path + file.getName()), 8 * 1024);
        boolean res = ftp.retrieveFile(ftpPath + file.getName(), buffOut);
        response.setIsOk(res ? SUCCESSFUL : FAIL);
        response.setMsg(fileType + "文件下载完成");
        buffOut.flush();
        buffOut.close();

        response.setFileName(file.getName());
        response.setFileType(fileType);
        response.setPath(path);
        SLog.d("FTPUtil(baseDown.java:221)" + fileType + "文件下载完成:" + res);

        if (!res) {
            return;
        }

        if (TextUtils.equals(fileType, "FACE")) {
            BusApp.getPosManager().setFaceListFileName(file.getName());
        }

    }

}
